package com.shiro;

import com.shiro.realm.CustomerRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;


/**
 * @author ：qs
 * @date ：Created in 2022/3/20
 * @description： 使用自定义realm
 * @modified By：
 */
public class TestCustomerRealmAuthenticator {

    public static void main(String[] args) {
        // 1. 创建securityManager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();

        // 2.1. 设置自定义realm
        // 不设置md5加密 可直接设置Realm
        // defaultSecurityManager.setRealm(new CustomerRealm());

        // 2.2. 设置自定义realm
        // 设置md5加密
        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);
        defaultSecurityManager.setRealm(customerRealm);


        // 3. 将安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        // 4. 通过安全工具类获取subject
        Subject subject = SecurityUtils.getSubject();

        // 5. 创建token
        UsernamePasswordToken token = new UsernamePasswordToken("xiaochen", "123");

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }
    }
}
